package emu.decvices.cpu;


import emu.decvices.bus.BusDevice;

/**
 * Random Access Memory 内存
 */
public class RAM extends BusDevice {
    private byte[] data = new byte[2*1024];//2KB

//    public RAM(){
//        show();
//    }

    @Override
    public int fromDeviceRead(int address) {
//        int index = shortAddressTransferIntIndex(address);
        //内存对应CPU的空间地址
        if (address < 0 || address >= 0x2000){
            return -1;
        }
        /*
            #0000-#07FF这2KB是RAM的容量，2k
            但是CPU对于RAM的地址空间为0000-2000 4倍于实际RAM容量
            因此，实际上#0000，#0800，#1000，#1800都是映射实际RAM第一个字节
            后面个空间镜像实际地址空间
         */
        return data[address%0x0800]&0xFF;
    }

    @Override
    public boolean toDeviceWrite(int address, int data) {
//        int index = shortAddressTransferIntIndex(address);
        //内存对应CPU的空间地址
        if (address < 0 || address >= 0x2000){
            return false;
        }
        address %= 0x0800;
        this.data[address]=(byte)(data&0x00FF);
        return true;
//        System.out.println(this);
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("     ");
        for (int i=0;i<16;i++){
            builder.append(String.format("%02X",i));
            builder.append(" ");
        }
        builder.append("\n\n");
        int row = 0;
        builder.append(String.format("%02X", row));
        builder.append("   ");
        for (int i = 0; i < 0x0100; i++) {
            builder.append(String.format("%02X",data[i]));
            builder.append(" ");
            if (i % 16 == 15&&i<0x100-1) {
                builder.append("\n");
                row++;
                builder.append(String.format("%02X", row));
                builder.append("   ");
            }
        }
        builder.append("\n");
        row = 0x8000;
        builder.append(String.format("%02X", row));
        builder.append("   ");
        for (int i = 0x8000; i <= 0x80F0; i++) {
            builder.append(String.format("%02X",fromBusRead(i)));
            builder.append(" ");
            if (i % 16 == 15&&i<0x80F0-1) {
                builder.append("\n");
                row++;
                builder.append(String.format("%02X", row));
                builder.append("   ");
            }
        }
        return builder.toString();
    }
}
